package com.big_data_studio.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.big_data_studio.entity.Menu;
import com.big_data_studio.entity.Role;
import com.big_data_studio.entity.RoleMenu;
import com.big_data_studio.mapper.MenuMapper;
import com.big_data_studio.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Autowired
    MenuMapper menuMapper;
    @Autowired
    IMenuService iMenuService;
    @Autowired
    RoleServiceImpl roleService;
    @Autowired
    UserRoleServiceImpl userRoleService;
    @Autowired
    RoleMenuServiceImpl roleMenuService;

    @Override
    public List<Menu> getMenuByUserId(Integer userId) {
        System.out.println("userId:" + userId);
        List<Integer> rids = roleService.listRolesByUserId(userId)
                .stream().map(Role::getId).collect(Collectors.toList());
        List<Integer> mids = roleMenuService.getMenuByRoleId(rids)
                .stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        System.out.println(mids);
        List<Menu> menus = iMenuService.listByIds(mids);
        handleMenus(menus);
        return menus;
    }

    public List<Menu> getAllByParentId(int parentId) {
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", parentId);
        return menuMapper.selectList(wrapper);
    }

    @Override
    public void handleMenus(List<Menu> menus) {
        menus.forEach(m -> {
            List<Menu> children = getAllByParentId(m.getId());
            m.setChildren(children);
        });
        menus.removeIf(m -> m.getParentId() != 0);
    }

}
